#-*- coding: utf-8 -*-

from ClassChat import *
from func import *

class u2u(object):
    def __init__(self):
        #изменяемое
        self.nick1= u'Некто 1'
        self.nick2 = u'Некто 2'
        self.isStart = False
        self.logchat = True

        self.timeout = 120
        self.autoStop = False
        self.getMessage = False

        #для класса
        self.oneStart = False
        self.oneStop = False
        self.client = Chat()
        self.client2 = Chat()

        self.lock_st = threading.Lock() #Локи - бог хитрости, сука бля
        self.locklog = threading.Lock()
        self.lock_message = threading.Lock()
        self.lock_handlestop = threading.Lock()
        self.lock_autostop = threading.Lock()

        self.file=''
        self.time = None
        self.event_stopChat = None


    #region spec func
    def log(self, txt):
        print txt
        if self.logchat:
            with self.locklog:
                try:
                    with open(self.file,'a+') as out:
                        txt +='\n'
                        out.write(txt.encode('utf-8'))
                except Exception, ex:
                    print ex
    def echo(self, msg):
        def wrap():
            self.log(msg)
        return wrap
    def message(self, nick, obj):
        def wrap(user, msg):
            with self.lock_message:
                if self.autoStop:
                    self.getMessage = True
                    self.autoStop = False

                if user=='im':
                    time = int((datetime.datetime.now()-self.time).total_seconds())
                    if time//60 >= 60:
                        self.log(u'(%02d:%02d:%02d) %s: %s' % (time//(60*60),time//60%60, time%60, nick, msg))
                    else:
                        self.log(u'(%02d:%02d) %s: %s' % (time//60, time%60, nick, msg))
                else:
                    obj.send(msg)
        return wrap
    def typing(self, name, obj):
        def wrap():
            if name=='start': obj.start_typing()
            else: obj.stop_typing()

    #endregion
    #region что-то с событиями
    def handle_start(self):
        print u'Первый подключен, подключаю второго...'
        self.client2.start()

    def handler2_start(self):
        self.isStart = True
        self.time = datetime.datetime.now()
        self.log(u'Чат начат')
        self.log(u'Url 1-го лога - http://chatvdvoem.ru/log?cid=%s&uid=%s' % (self.client.cid, self.client.uid))
        self.log(u'Url 2-го лога - http://chatvdvoem.ru/log?cid=%s&uid=%s' % (self.client2.cid, self.client2.uid))

    def eventsload(self):
        self.client2.event_startChat = self.handler2_start
        self.client2.event_stopChat = self.handle_stop
        self.client2.event_newMessage = self.message(self.nick2, self.client)
        self.client2.event_startTyping = self.typing('start', self.client)
        self.client2.event_stopTyping = self.typing('stop', self.client)

        self.client.event_startChat=self.handle_start
        self.client.event_stopChat=self.handle_stop
        self.client.event_newMessage = self.message(self.nick1, self.client2)
        self.client.event_startTyping = self.typing('start', self.client2)
        self.client.event_stopTyping = self.typing('stop', self.client2)
    #endregion

    def handle_autostop(self):
        with self.lock_autostop:
            if not self.getMessage:
                self.handle_stop()
            else:
                self.getMessage = False
                #threading.Timer(self.timeout, self.handle_autostop).start()

    def start(self):
        with self.lock_st:
            if self.client.isStart or self.client2.isStart:
                print u'Чат уже запущен'
                return

            self.isStart = True
            self.oneStop = False
            if not self.oneStart:
                self.eventsload()
                self.oneStart = True
                if self.autoStop:
                    threading.Timer(self.timeout, self.handle_autostop).start()
                self.file = 'log__%s.txt' % datetime.datetime.now().strftime("%H-%M-%S %Y_%m_%d")

        print u'Начинаю...'
        self.client.start()

    def stop(self):
        with self.lock_st:
            if self.client.isStart or self.client2.isStart:
                self.handle_stop()
            else:
                print u'Чат не запущен'

    def handle_stop(self):
        with self.lock_handlestop:
            if self.client.isStart: self.client.stop()
            if self.client2.isStart: self.client2.stop()

            if not self.oneStop:
                if (not self.client.isStart) and (not self.client2.isStart):
                    self.oneStop = True
                    self.isStart = False
                    self.log(u'Чат завершен')
                    self.log(u'\n')
                    if self.event_stopChat:
                        run_thread(self.event_stopChat)


    def send(self, num, txt):
        if num == 0:
            self.client.send(txt)
            self.client2.send(txt)

        elif num==1:
            self.client.send(txt)

        elif num==2:
            self.client2.send(txt)

